package com.luyou.a05;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.annotation.PostConstruct;

/**
 * 注册创建完成的bean
 * @author 28336
 * @version 1.0
 * Create by 2023/12/19 20:12
 */
public class TestBeanFactoryPostProcessor {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.registerBean("bean2", Bean2.class);
        context.registerBean(MyBeanFactoryPostProcessor.class);
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }
        System.out.println("========================>");
        /**
         * BeanDefinition 的名称数组中不包含 bean1，
         * 也没有输出任何与经过 Spring 生命周期相关的日志信息，
         * 容器中 bean1 里注入的 bean2 也是 null。这表明通过这种方式注册的 Bean
         * 不会注册 BeanDefinition，也不会经过 Spring 生命周期。
         */
        System.out.println(context.getBean(Bean1.class));

    }

    static class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor{

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            Bean1 bean1 = new Bean1();
            bean1.setName("luyou");
            beanFactory.registerSingleton("bean1", bean1);
        }
    }

    @Getter
    @ToString
    static class Bean1 {
        @Setter
        private String name;
        private Bean2 bean2;

        @Autowired
        private void setBean2(Bean2 bean2) {
            System.out.println(this + "依赖注入 bean2");
            this.bean2 = bean2;
        }

        @PostConstruct
        public void init() {
            System.out.println(this  + "初始化...");
        }
    }

    static class Bean2 {
    }
}
